package com.secneo.appshare.activities;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.impl.HttpComm;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;
import com.secneo.mp.api.database.DatabaseHelper;

public class MemberSettingHeaderActivity extends Activity
{
	private TextView mAndroidIdText;
	private String androidId = "";
	private String uid = "";
	
	private Gallery mGallery;
	private Drawable[] mAssertImages;
	private int currentImageId = 1;
	private TextView memberAvatarsLocalSaveImageView;
	private TextView memberAvatarsPhotoChoiceImageView, memberAvatarsPhotoSaveImageView;
	private ImageView memberChoiceHeadImageView;
	Dialog dialog = null;
	int id_dialog6 = 0;
	private String uploadPhotoUrl = "";
	private String savePhotoPath = "";
	private Bitmap bitmapGallery = null;
	private Bitmap bitmapCamera = null;
	private ImageAdapter imageAdatper = null;
	
	/* 用来标识请求照相功能的activity */
	private static final int CAMERA_WITH_DATA = 3023;
	/* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
	private Button register1Button;
	private ProgressDialog mNetProgressBar = null;
	public Handler mHandler1 = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case 0:
					if (mNetProgressBar != null)
					{
						mNetProgressBar.dismiss();
						mNetProgressBar = null;
					}
					Toast.makeText(MemberSettingHeaderActivity.this, "头像保存成功", Toast.LENGTH_SHORT).show();
					break;
				case 1:
					if (mNetProgressBar != null)
					{
						mNetProgressBar.dismiss();
						mNetProgressBar = null;
					}
					Toast.makeText(MemberSettingHeaderActivity.this, "头像保存失败", Toast.LENGTH_SHORT).show();
					break;
				case 4:
					if (mNetProgressBar != null)
					{
						mNetProgressBar.dismiss();
						mNetProgressBar = null;
					}
					Toast.makeText(MemberSettingHeaderActivity.this, "网络异常，请检查网络连接", Toast.LENGTH_SHORT).show();
					break;
				default:
					if (mNetProgressBar != null)
					{
						mNetProgressBar.dismiss();
						mNetProgressBar = null;
					}
					Toast.makeText(MemberSettingHeaderActivity.this, "网络异常，请检查网络连接", Toast.LENGTH_SHORT).show();
					break;

			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.member_setting_header);
		AppShareApplication.getInstance().addActivity(this);
		refreshModifyHeaderView();

		mAndroidIdText = (TextView) findViewById(R.id.bid);
		androidId = LocalStore.getLocaleStoreInstance().getAndroidId();
		uid = LocalStore.getLocaleStoreInstance().getUid();
		mAndroidIdText.setText(androidId);

		Button retBtn = (Button) findViewById(R.id.img_ret);
		retBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		ImageView homeBtn = (ImageView) findViewById(R.id.img_home);
		homeBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent();
				intent.setClass(MemberSettingHeaderActivity.this, MainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				finish();
			}
		});

		register1Button = (Button) findViewById(R.id.Register1Button);
		Bundle bundle = getIntent().getExtras();
		boolean register_flag = bundle.getBoolean("registerFlag");
		if (register_flag)
		{
			register1Button.setVisibility(View.VISIBLE);
		}
		register1Button.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				DatabaseHelper dh=new DatabaseHelper(MemberSettingHeaderActivity.this);
				dh.insertUserAppPopularityBycatagory(MemberSettingHeaderActivity.this,2048);
				dh.close();
				
				String avatar = LocalStore.getLocaleStoreInstance().getAvatarName();
				Log.d("MyTag", "register avatar getAvatarName=" + avatar);
				if ("".equals(avatar) || avatar == null)
				{
					saveLoalPhoto();
				}
				Intent intent = new Intent();
				Bundle mBundle = new Bundle();
				mBundle.putInt("sns_type", 0);
				intent.putExtras(mBundle);
				intent.setClass(MemberSettingHeaderActivity.this, ChooseUserActivity.class);
				startActivity(intent);
				finish();
			}
		});
	}

	@Override
	protected void onDestroy()
	{
		if(bitmapGallery != null)
		{
			bitmapGallery.recycle();
			bitmapGallery = null;
		}
		if(bitmapCamera != null)
		{
			bitmapCamera.recycle();
			bitmapCamera = null;
		}
		if(imageAdatper != null)
			imageAdatper.freeDrawable();
		System.gc();
		super.onDestroy();
	}

	// 修改头像
	private void refreshModifyHeaderView()
	{
		mGallery = (Gallery) findViewById(R.id.gallery_avatars);
		memberAvatarsLocalSaveImageView = (TextView) findViewById(R.id.MemberAvatarsLocalSaveImageView);
		memberAvatarsPhotoChoiceImageView = (TextView) findViewById(R.id.MemberAvatarsPhotoChoiceImageView);
		memberChoiceHeadImageView = (ImageView) findViewById(R.id.MemberChoiceHeadImageView);
		memberAvatarsPhotoSaveImageView = (TextView) findViewById(R.id.MemberAvatarsPhotoSaveImageView);
		mAssertImages = new Drawable[Constants.AVATAR_ICON_NUMBER];
		try
		{
			for (int i = 1; i <= Constants.AVATAR_ICON_NUMBER; i++)
			{
				String imageName = "buildin:";
				if (i < 10) {
					imageName = imageName + "0" + i;
				} else {
					imageName = imageName + i;
				}
				mAssertImages[i - 1] = Util.getDrawableFromAsset(MemberSettingHeaderActivity.this, imageName);
			}
			
		} catch (IOException ex)
		{
			ex.printStackTrace();
			return;
		}
		imageAdatper = new ImageAdapter(this, mAssertImages);
		mGallery.setAdapter(imageAdatper);

		memberAvatarsLocalSaveImageView.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				DatabaseHelper dh=new DatabaseHelper(MemberSettingHeaderActivity.this);
				dh.insertUserAppPopularityBycatagory(MemberSettingHeaderActivity.this,2054);
				dh.close();
				
				saveLoalPhoto();
			}
		});

		memberAvatarsPhotoChoiceImageView.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				choicePhoto();
			}
		});

		memberAvatarsPhotoSaveImageView.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub

				DatabaseHelper dh=new DatabaseHelper(MemberSettingHeaderActivity.this);
				dh.insertUserAppPopularityBycatagory(MemberSettingHeaderActivity.this,2047);
				dh.close();
				
				if (!"".equals(uploadPhotoUrl) && uploadPhotoUrl != null)
				{
					mNetProgressBar = ProgressDialog.show(MemberSettingHeaderActivity.this, null, "正在保存头像中...", true);
					Thread avatarstupianThread = new Thread()
					{
						public void run()
						{
							String uid = LocalStore.getLocaleStoreInstance(MemberSettingHeaderActivity.this).getUid();
							Log.v("myLog", uploadPhotoUrl);
							File f = new File(uploadPhotoUrl);

							JSONObject str_response = HttpComm.uploadFile(Constants.URL + Constants.UPLOAD_PHOTO_URL, f, uid);
							if (str_response != null)
							{
								String status = null;
								try
								{
									status = str_response.getString("status");
									if ("ok".equals(status))
									{
										String photoPath = str_response.getString("photoPath");
										LocalStore.getLocaleStoreInstance(MemberSettingHeaderActivity.this).overrideAvatarName(Constants.SERVER_ICON_URL + photoPath);
										Log.v("MyTag", Constants.SERVER_ICON_URL + photoPath);
										Message msg = new Message();
										msg.what = 0;
										mHandler1.sendMessage(msg);
									} else
									{
										Message msg = new Message();
										msg.what = 1;
										mHandler1.sendMessage(msg);
									}
									Log.v("MyTag", status);
								} catch (JSONException e)
								{
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							} else
							{
								Message msg = new Message();
								msg.what = 4;
								mHandler1.sendMessage(msg);
							}
						}
					};
					avatarstupianThread.start();
				} else
				{
					Toast.makeText(MemberSettingHeaderActivity.this, "请选择图片", Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	public void saveLoalPhoto()
	{
		currentImageId = 1;
		int itemPostion = mGallery.getSelectedItemPosition();
		if(Gallery.INVALID_POSITION != itemPostion){
			currentImageId = itemPostion + 1;
		}
		Log.e("MyTag", "Avatar Id: "+currentImageId);
		
		final String avatarStr;
		if (currentImageId < 10)
			avatarStr = "buildin:0" + String.valueOf(currentImageId);
		else
			avatarStr = "buildin:" + String.valueOf(currentImageId);
		LocalStore.getLocaleStoreInstance(MemberSettingHeaderActivity.this).overrideAvatarName(avatarStr);
		Log.d("MyTag", "setAvatarName... avatar =" + avatarStr);
		mNetProgressBar = ProgressDialog.show(this, null, "正在保存头像中...", true);
		Thread tupianThread = new Thread()
		{
			public void run()
			{
				String uid = LocalStore.getLocaleStoreInstance(MemberSettingHeaderActivity.this).getUid();
				Map<String, String> params = new HashMap<String, String>();
				params.put("userId", uid);
				params.put("avatar", avatarStr);
				// str_response="1001";
				JSONObject str_response = HttpComm.doPost(Constants.URL + Constants.UPLOAD_PHOTO_URL, params);
				try
				{
					if (str_response != null)
					{
						String status = str_response.getString("status");
						if ("ok".equals(status))
						{
							Message msg = new Message();
							msg.what = 0;
							mHandler1.sendMessage(msg);
						} else
						{
							Message msg = new Message();
							msg.what = 1;
							mHandler1.sendMessage(msg);
						}
						Log.v("myTag", status);
					} else
					{
						Message msg = new Message();
						msg.what = 4;
						mHandler1.sendMessage(msg);
					}
				} catch (JSONException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// Log.v("myTag",str_response);
			}
		};
		tupianThread.start();

	}

	public void choicePhoto()
	{
		new AlertDialog.Builder(MemberSettingHeaderActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("选择图片来源").setSingleChoiceItems(new String[]
		{ "从相机", "从媒体库" },
		// 用 id_dialog6 记录那个 RadioButton 被选中
				id_dialog6, new DialogInterface.OnClickListener()
				{

					public void onClick(DialogInterface dialog, int which)

					{
						id_dialog6 = which;
					}

				}).setPositiveButton("确定", new DialogInterface.OnClickListener()

		{
			public void onClick(DialogInterface dialog, int which)
			{

				String tmpstr = "";
				if (id_dialog6 == 0)
					photo();
				// tmpstr = "Item1 is selected";
				else
					// tmpstr = "Item2 is selected";
					doPickPhotoFromGallery();
				Toast.makeText(MemberSettingHeaderActivity.this, tmpstr, Toast.LENGTH_LONG).show();
				dialog.dismiss(); // 可以没有这句
			}
		}).create().show();
	}

	public void photo()
	{
		try
		{

			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			savePhotoPath = PHOTO_DIR + "/" + getPhotoFileName();
			File out = new File(savePhotoPath);

			Uri uri = Uri.fromFile(out);

			intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
			startActivityForResult(intent, CAMERA_WITH_DATA);

		} catch (Exception e)
		{

			e.printStackTrace();

		}
	}

	public class ImageAdapter extends BaseAdapter
	{
		private Context ctx;
		int GalItemBg;
		private Drawable[] mImageArray;

		public ImageAdapter(Context ctx, Drawable[] imageArray)
		{
			this.ctx = ctx;
			this.mImageArray = imageArray;
			TypedArray typeArray = obtainStyledAttributes(R.styleable.GalleryTheme);
			GalItemBg = typeArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
			typeArray.recycle();
		}
		
		public void freeDrawable()
		{
			for(int i=0; i<mImageArray.length; i++)
			{
				mImageArray[i] = null;
			}
			System.gc();
		}

		@Override
		public int getCount()
		{
			return mImageArray.length;
		}

		@Override
		public Object getItem(int position)
		{
			return position;
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			final ImageView imgView = new ImageView(ctx);
			imgView.setImageDrawable(mImageArray[position]);
			imgView.setScaleType(ImageView.ScaleType.FIT_XY);
			imgView.setBackgroundResource(GalItemBg);
			return imgView;
		}

	}

	// 请求Gallery程序
	protected void doPickPhotoFromGallery()
	{
		try
		{
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);

		} catch (ActivityNotFoundException e)
		{
			Toast.makeText(this, "photoPickerNotFoundText1",Toast.LENGTH_LONG).show();
		}

	}

	// 封装请求Gallery的intent
	public static Intent getPhotoPickIntent()
	{
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	// 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (resultCode != RESULT_OK)
			return;

		switch (requestCode)
		{
			case PHOTO_PICKED_WITH_DATA:
			{
				// 调用Gallery返回的
				String photoName = "appsharephoto1.jpg";
				final Bitmap photo = data.getParcelableExtra("data");

				String photoPath = storeImageToFile(photo, photoName);
				Log.v("", "pathString = " + photoPath);
				bitmapGallery = BitmapFactory.decodeFile(photoPath);
				memberChoiceHeadImageView.setImageBitmap(bitmapGallery);
				break;
			}

			case CAMERA_WITH_DATA:
			{
				// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
				try
				{
					Intent cj1 = new Intent("com.android.camera.action.CROP");
					try
					{
						cj1.setData(Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), savePhotoPath, null, null)));
					} catch (Exception e)
					{
						e.printStackTrace();
					}
					cj1.putExtra("crop", "true");
					cj1.putExtra("aspectX", 3);
					cj1.putExtra("aspectY", 2);
					cj1.putExtra("outputX", 384);
					cj1.putExtra("outputY", 256);
					cj1.putExtra("return-data", true);
					startActivityForResult(cj1, 2);

					File camera = new File(savePhotoPath);
					if (camera.exists())
						camera.delete();

				} catch (Exception e)
				{
					e.printStackTrace();
				}
				break;
			}
			case 2:
			{
				String photoName = "appsharephoto1.jpg";
				final Bitmap photo = data.getParcelableExtra("data");

				String photoPath = storeImageToFile(photo, photoName);
				Log.v("", "pathString = " + photoPath);
				bitmapCamera = BitmapFactory.decodeFile(photoPath);
				memberChoiceHeadImageView.setImageBitmap(bitmapCamera);
				break;
			}

		}
	}

	protected void doCropPhoto(File f)
	{
		try
		{
			// 启动gallery去剪辑这个照片
			final Intent intent = getCropImageIntent(Uri.fromFile(f));
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
			
		} catch (Exception e)
		{
			Toast.makeText(this, "photoPickerNotFoundText", Toast.LENGTH_LONG).show();
		}

	}

	/**
	 * Constructs an intent for image cropping. 调用图片剪辑程序
	 */
	public static Intent getCropImageIntent(Uri photoUri)
	{
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	/**
	 * Store image to SD card.
	 */
	private String storeImageToFile(Bitmap photo, String photoName)
	{
		try
		{
			File file = new File(PHOTO_DIR, photoName);
			FileOutputStream outStreamz = new FileOutputStream(file);

			photo.compress(Bitmap.CompressFormat.PNG, 50, outStreamz);

			outStreamz.close();
			uploadPhotoUrl = PHOTO_DIR + "/" + photoName;
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
			return null;
		} catch (IOException e)
		{
			e.printStackTrace();
			return null;
		}
		return uploadPhotoUrl;
	}

	/**
	 * 用当前时间给取得的图片命名
	 * 
	 */
	private String getPhotoFileName()
	{
		return System.currentTimeMillis() + ".jpg";
	}

}
